package com.polaris.live.adapter.backpack

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterInside
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.BaseQuickAdapter
import com.polaris.live.R
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.util.AppCodeUtils
import com.polaris.live.databinding.AdapterBackpackBubbleBinding
import com.polaris.live.databinding.AdapterBackpackBubbleLiveEffectBinding
import com.polaris.live.databinding.AdapterBackpackBubblePartyBackgroundBinding
import com.polaris.live.databinding.AdapterBackpackBubbleUserProfileBinding
import com.polaris.live.resp.back_resp.UserBackpackDecorationResp
import com.polaris.live.translation.R.string
import com.polaris.live.ui.backpack.fragment.BackpackFragment
import com.polaris.live.utils.CommonUtils.toBoolean
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.transformRounded
import com.polaris.live.widget.refresh.BaseBindingViewHolder
import java.util.concurrent.TimeUnit

/**
 * BackPackBubbleAdapter
 *
 * @author Created by 半仙 on 2024/1/31/031 11:44
 */
class BackPackBubbleAdapter :
    BaseQuickAdapter<UserBackpackDecorationResp, BaseBackPackBubbleHolder<*, UserBackpackDecorationResp>>(0) {

    private var mSelectIndex = -1

    init {
        addChildClickViewIds(R.id.tv_chick, R.id.tv_chick1)
    }

    override fun getDefItemViewType(position: Int): Int {
        return data[position].decorationType.toInt()
    }

    override fun onCreateDefViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): BaseBackPackBubbleHolder<*, UserBackpackDecorationResp> {
        return when (viewType) {
            CommonConst.DressUp.PARTY_BACKGROUND.toInt() -> {
                BackPackBubblePartyBackgroundHolder(
                    AdapterBackpackBubblePartyBackgroundBinding.inflate(
                        LayoutInflater.from(parent.context),
                        parent,
                        false
                    )
                )
            }

            CommonConst.DressUp.LIVE_EFFECT.toInt() -> {
                BackPackBubbleLiveEffectHolder(
                    AdapterBackpackBubbleLiveEffectBinding.inflate(
                        LayoutInflater.from(parent.context),
                        parent,
                        false
                    )
                )
            }

            CommonConst.DressUp.USER_PROFILE.toInt() -> {
                BackPackBubbleUserProfileHolder(
                    AdapterBackpackBubbleUserProfileBinding.inflate(
                        LayoutInflater.from(parent.context),
                        parent,
                        false
                    )
                )
            }

            else -> {
                BackPackBubbleHolder(
                    AdapterBackpackBubbleBinding.inflate(
                        LayoutInflater.from(parent.context),
                        parent,
                        false
                    )
                )
            }

        }

    }

    override fun convert(
        holder: BaseBackPackBubbleHolder<*, UserBackpackDecorationResp>,
        item: UserBackpackDecorationResp,
    ) {
        holder.setSelect(mSelectIndex)
        holder.bind(item)
    }

    override fun convert(
        holder: BaseBackPackBubbleHolder<*, UserBackpackDecorationResp>,
        item: UserBackpackDecorationResp, data: List<Any>,
    ) {
        when (data.getOrNull(0)) {
            "notify" -> holder.notifyItem(item)
            "show" -> holder.show()
            "hide" -> holder.hide()
        }
    }

    fun setSelect(position: Int) {
        notifyItemChanged(mSelectIndex)

        mSelectIndex = position

        notifyItemChanged(mSelectIndex)
    }

    fun getLastSelect() = mSelectIndex

    companion object {

        const val NOT_HAVE = -1L             //装扮id等于-1是未获取
    }

    class BackPackBubbleHolder(binding: AdapterBackpackBubbleBinding) :
        BaseBackPackBubbleHolder<AdapterBackpackBubbleBinding, UserBackpackDecorationResp>(binding) {

        private var mSelectIndex = -1

        override fun setSelect(position: Int) {
            mSelectIndex = position
        }

        override fun notifyItem(item: UserBackpackDecorationResp) {
            setTime(item)
        }

        override fun show() {
            mBinding.tvName.startAndResume()
        }

        override fun hide() {
            mBinding.tvName.pause()
        }

        override fun bind(item: UserBackpackDecorationResp) {
            mBinding.apply {
                val position = absoluteAdapterPosition
                if (position == mSelectIndex) {
                    consTitle.setBackgroundResource(R.drawable.back_pack_select_back)
                } else {
                    consTitle.setBackgroundResource(R.drawable.r8_back_ffffff)
                }
                if (item.useStatus.toBoolean()) {
                    tvUsering.visibility = View.VISIBLE
                    tvChick1.visibility = View.VISIBLE
                    tvChick.visibility = View.GONE
                } else {
                    tvChick1.visibility = View.GONE
                    tvChick.visibility = View.VISIBLE
                    tvUsering.visibility = View.GONE
                }
                tvName.setText(item.name, true)
                //如果未获取
                if (item.backpackId == NOT_HAVE) {
                    Glide.with(icImage).load(ImageUtils.imgPath(item.displayUrl)).into(icImage)
                    llTag.visibility = View.INVISIBLE
                    tvChick.visibility = View.GONE
                    tvChick1.visibility = View.GONE
                    ivNotGetIt.visibility = View.VISIBLE
                    icImage.alpha = 0.4f
                } else {
                    ivNotGetIt.visibility = View.GONE
                    Glide.with(icImage).load(ImageUtils.imgPath(item.displayUrl)).into(icImage)
                    llTag.visibility = View.VISIBLE
                    setTime(item)
                    icImage.alpha = 1f
                }
            }

        }

        private fun setTime(item: UserBackpackDecorationResp) {
            mBinding.apply {
                val expiredTime = item.expiredTime
                if (expiredTime.isNullOrEmpty()) {
                    ivTimeIcon.visibility = View.GONE
                    tvTime.text = StringUtils.getString(string.permanent)
                } else {
                    ivTimeIcon.visibility = View.VISIBLE
                    item.expireDays?.let {
                        if (it == 0L) {
                            tvTime.text = formatTime(expiredTime.toLong() - CacheUtil.getServerTime())
                        } else {
                            val (day, num) = if (it < 365) {
                                "day" to it
                            } else {
                                "year" to it / 365
                            }
                            tvTime.text = "$num$day"
                        }
                    }
                }
            }
        }
    }

    class BackPackBubblePartyBackgroundHolder(binding: AdapterBackpackBubblePartyBackgroundBinding) :
        BaseBackPackBubbleHolder<AdapterBackpackBubblePartyBackgroundBinding, UserBackpackDecorationResp>(binding) {

        private var mSelectIndex = -1

        override fun setSelect(position: Int) {
            mSelectIndex = position
        }

        override fun notifyItem(item: UserBackpackDecorationResp) {
            setTime(item)
        }

        override fun show() {
            mBinding.tvName.startAndResume()
        }

        override fun hide() {
            mBinding.tvName.pause()
        }

        override fun bind(item: UserBackpackDecorationResp) {
            mBinding.apply {
                val position = absoluteAdapterPosition
                if (position == mSelectIndex) {
                    consTitle.setBackgroundResource(R.drawable.back_pack_select_back)
                } else {
                    consTitle.setBackgroundResource(R.drawable.r8_back_ffffff)
                }

                if (item.backpackId == BackpackFragment.DEFUSERBACKPACKDECORATION) {
                    ivTimeIcon.visibility = View.GONE
                    tvTime.text = StringUtils.getString(string.permanent)
                    tvName.setText(StringUtils.getString(string.default_background), true)
                    Glide.with(icImage).load(R.drawable.default_party_bg).transformRounded(4.autoDp).into(icImage)
                    tvChick1.visibility = View.INVISIBLE
                    ivNotGetIt.visibility = View.INVISIBLE
                    if (item.useStatus.toBoolean()) {
                        tvUsering.visibility = View.VISIBLE
                        tvChick.visibility = View.INVISIBLE
                    } else {
                        tvUsering.visibility = View.GONE
                        tvChick.visibility = View.VISIBLE
                    }
                } else {
                    if (item.useStatus.toBoolean()) {
                        tvUsering.visibility = View.VISIBLE
                        tvChick1.visibility = View.VISIBLE
                        tvChick.visibility = View.GONE
                    } else {
                        tvChick1.visibility = View.GONE
                        tvChick.visibility = View.VISIBLE
                        tvUsering.visibility = View.GONE
                    }
                    tvName.setText(item.name, true)
                    //如果未获取
                    if (item.backpackId == NOT_HAVE) {
                        Glide.with(icImage).load(ImageUtils.imgPath(item.displayUrl)).into(icImage)
                        icImage.alpha = 0.4f
                        llTag.visibility = View.INVISIBLE
                        tvChick.visibility = View.GONE
                        tvChick1.visibility = View.GONE
                        ivNotGetIt.visibility = View.VISIBLE
                    } else {
                        ivNotGetIt.visibility = View.GONE
                        Glide.with(icImage)
                            .load(ImageUtils.imgPath(item.displayUrl))
                            .transformRounded(4.autoDp)
                            .into(icImage)
                        llTag.visibility = View.VISIBLE
                        setTime(item)
                        icImage.alpha = 1f
                    }

                }

            }

        }

        private fun setTime(item: UserBackpackDecorationResp) {
            mBinding.apply {
                val expiredTime = item.expiredTime
                if (expiredTime.isNullOrEmpty()) {
                    ivTimeIcon.visibility = View.GONE
                    tvTime.text = StringUtils.getString(string.permanent)
                } else {
                    ivTimeIcon.visibility = View.VISIBLE
                    item.expireDays?.let {
                        if (it == 0L) {
                            tvTime.text = formatTime(expiredTime.toLong() - CacheUtil.getServerTime())
                        } else {
                            val (day, num) = if (it < 365) {
                                "day" to it
                            } else {
                                "year" to it / 365
                            }
                            tvTime.text = "$num$day"
                        }
                    }
                }
            }
        }
    }

    class BackPackBubbleLiveEffectHolder(binding: AdapterBackpackBubbleLiveEffectBinding) :
        BaseBackPackBubbleHolder<AdapterBackpackBubbleLiveEffectBinding, UserBackpackDecorationResp>(binding) {

        private var mSelectIndex = -1

        override fun setSelect(position: Int) {
            mSelectIndex = position
        }

        override fun notifyItem(item: UserBackpackDecorationResp) {
            setTime(item)
        }

        override fun show() {
            mBinding.tvName.startAndResume()
        }

        override fun hide() {
            mBinding.tvName.pause()
        }

        override fun bind(item: UserBackpackDecorationResp) {
            mBinding.apply {
                val position = absoluteAdapterPosition
                if (position == mSelectIndex) {
                    consTitle.setBackgroundResource(R.drawable.back_pack_select_back)
                } else {
                    consTitle.setBackgroundResource(R.drawable.r8_back_ffffff)
                }
                if (item.useStatus.toBoolean()) {
                    tvUsering.visibility = View.VISIBLE
                    tvChick1.visibility = View.VISIBLE
                    tvChick.visibility = View.GONE
                } else {
                    tvChick1.visibility = View.GONE
                    tvChick.visibility = View.VISIBLE
                    tvUsering.visibility = View.GONE
                }
                tvName.setText(item.name, true)
                //如果未获取
                if (item.backpackId == NOT_HAVE) {
                    Glide.with(icImage).load(ImageUtils.imgPath(item.displayUrl)).into(icImage)
                    icImage.alpha = 0.4f
                    llTag.visibility = View.INVISIBLE
                    tvChick.visibility = View.GONE
                    tvChick1.visibility = View.GONE
                    ivNotGetIt.visibility = View.VISIBLE
                } else {
                    ivNotGetIt.visibility = View.GONE
                    Glide.with(icImage)
                        .load(ImageUtils.imgPath(item.displayUrl))
                        .apply(RequestOptions().transform(CenterInside(), RoundedCorners(4.autoDp)))
                        .into(icImage)
                    llTag.visibility = View.VISIBLE
                    setTime(item)
                    icImage.alpha = 1f
                }
                if (AppCodeUtils.isAR()) {
                    icImage.scaleX = -1f
                }

            }

        }

        private fun setTime(item: UserBackpackDecorationResp) {
            mBinding.apply {
                val expiredTime = item.expiredTime
                if (expiredTime.isNullOrEmpty()) {
                    ivTimeIcon.visibility = View.GONE
                    tvTime.text = StringUtils.getString(string.permanent)
                } else {
                    ivTimeIcon.visibility = View.VISIBLE
                    item.expireDays?.let {
                        if (it == 0L) {
                            tvTime.text = formatTime(expiredTime.toLong() - CacheUtil.getServerTime())
                        } else {
                            val (day, num) = if (it < 365) {
                                "day" to it
                            } else {
                                "year" to it / 365
                            }
                            tvTime.text = "$num$day"
                        }
                    }
                }
            }
        }

    }

    class BackPackBubbleUserProfileHolder(binding: AdapterBackpackBubbleUserProfileBinding) :
        BaseBackPackBubbleHolder<AdapterBackpackBubbleUserProfileBinding, UserBackpackDecorationResp>(binding) {

        private var mSelectIndex = -1

        override fun setSelect(position: Int) {
            mSelectIndex = position
        }

        override fun notifyItem(item: UserBackpackDecorationResp) {
            setTime(item)
        }

        override fun show() {
            mBinding.tvName.startAndResume()
        }

        override fun hide() {
            mBinding.tvName.pause()
        }

        override fun bind(item: UserBackpackDecorationResp) {
            mBinding.apply {
                val position = absoluteAdapterPosition
                if (position == mSelectIndex) {
                    consTitle.setBackgroundResource(R.drawable.back_pack_select_back)
                } else {
                    consTitle.setBackgroundResource(R.drawable.r8_back_ffffff)
                }
                if (item.useStatus.toBoolean()) {
                    tvUsering.visibility = View.VISIBLE
                    tvChick1.visibility = View.VISIBLE
                    tvChick.visibility = View.GONE
                } else {
                    tvChick1.visibility = View.GONE
                    tvChick.visibility = View.VISIBLE
                    tvUsering.visibility = View.GONE
                }
                tvName.setText(item.name, true)
                //如果未获取
                if (item.backpackId == NOT_HAVE) {
                    Glide.with(icImage).load(ImageUtils.imgPath(item.displayUrl)).into(icImage)
                    icImage.alpha = 0.4f
                    llTag.visibility = View.INVISIBLE
                    tvChick.visibility = View.GONE
                    tvChick1.visibility = View.GONE
                    ivNotGetIt.visibility = View.VISIBLE
                } else {
                    ivNotGetIt.visibility = View.GONE
                    Glide.with(icImage)
                        .load(ImageUtils.imgPath(item.displayUrl))
                        .apply(RequestOptions().transform(CenterInside(), RoundedCorners(4.autoDp)))
                        .into(icImage)
                    llTag.visibility = View.VISIBLE
                    setTime(item)
                    icImage.alpha = 1f
                }
            }

        }

        private fun setTime(item: UserBackpackDecorationResp) {
            mBinding.apply {
                val expiredTime = item.expiredTime
                if (expiredTime.isNullOrEmpty()) {
                    ivTimeIcon.visibility = View.GONE
                    tvTime.text = StringUtils.getString(string.permanent)
                } else {
                    ivTimeIcon.visibility = View.VISIBLE
                    item.expireDays?.let {
                        if (it == 0L) {
                            tvTime.text = formatTime(expiredTime.toLong() - CacheUtil.getServerTime())
                        } else {
                            val (day, num) = if (it < 365) {
                                "day" to it
                            } else {
                                "year" to it / 365
                            }
                            tvTime.text = "$num$day"
                        }
                    }
                }
            }
        }
    }
}

abstract class BaseBackPackBubbleHolder<VB : ViewBinding, T>(binding: VB) :
    BaseBindingViewHolder<VB, T>(binding) {

    open fun setSelect(position: Int) {

    }

    open fun notifyItem(item: T) {

    }

    open fun show() {

    }

    open fun hide() {

    }

    fun formatTime(timeInMillis: Long): String {
        val days = TimeUnit.MILLISECONDS.toDays(timeInMillis)
        val hours = TimeUnit.MILLISECONDS.toHours(timeInMillis)
        val minutes = TimeUnit.MILLISECONDS.toMinutes(timeInMillis)
        val seconds = TimeUnit.MILLISECONDS.toSeconds(timeInMillis)
        return when {
            days > 0 -> StringUtils.getString(string.days, days)
            hours > 0 -> StringUtils.getString(string.hours, hours)
            minutes > 0 -> StringUtils.getString(string.minutes, minutes)
            seconds > 0 -> StringUtils.getString(string.seconds, seconds)
            else -> StringUtils.getString(string.expired)
        }
    }
}